package article_management;
import java.util.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
public class FileArtical{
	private ObjectInputStream ois=null;
	private ObjectOutputStream oos=null; 
	private FileInputStream fis=null;
	private FileOutputStream fos=null;
	public static String FolderContent="Content";
	
	public FileArtical(){
		checkDir("Content");
		checkDir("AutoID");
		checkDir("Restore");
	}	
	private void checkDir(String dir){
		File f=new File(dir);
		if(!f.exists())
			f.mkdir();
	}
	public static void setFile(String ft){
		FolderContent=ft;
	}
	//====================  Read data from File =============================
	public Artical read(String filename) {
		Artical ar=new Artical();
		BufferedInputStream b=null;
		File f=new File(FolderContent+File.separator+filename+".txt");
		if(!f.exists()){
			return ar;
		}
		else{
			try{
				fis=new FileInputStream(f);
				b=new BufferedInputStream(fis);
				ois=new ObjectInputStream(b);
				ar=(Artical)ois.readObject(); //Read from file to Artical
				fis.close();
				ois.close();
			}catch(FileNotFoundException e){
				System.out.println(e.getMessage());
			}catch(Exception e){
				System.err.println(e.getMessage());
			}
		}
		return ar;
	}
 
	
	//==================== Write data to File ==============================
	public boolean write(String filename,Artical ar) {
		File ft=new File(FolderContent+File.separator+filename+".txt");
		BufferedOutputStream bos=null;
		try{
			fos=new FileOutputStream(ft);
			bos=new BufferedOutputStream(fos);
			oos=new ObjectOutputStream(bos);
			
				oos.writeObject(ar);// Write new artical to file
				oos.flush();
				oos.close();
			
			return true;
		}catch(FileNotFoundException e){
			System.out.println(e);
		}
		catch(Exception e){
			
			System.out.println(e.getMessage());
		}
		
		return false;
	}
	//======================== Update data ==============================
	public boolean Update(String filename,Artical ar){
		File f=new File(FolderContent+File.separator+filename+".txt");
		if(!f.exists())
			return false;
		if(write(filename,ar))
			return true;
		return false;
	}
	//======================== Delete Data ============================
	public boolean Delete(String filename) throws IOException {
		File ft=new File(FolderContent+File.separator+filename+".txt");
		if(!ft.exists())
			return false;
		copyFile(FolderContent,"Restore",filename);
		boolean success=ft.delete();
		if(success){
			return true;
		}
		
		return false;
	}
	//=================== Search all Content Data ==============================
	public ArrayList<Integer> Search(String str){
		ArrayList<Integer> a=new ArrayList();
		Artical ar=null;
		int filename=0;
		File ff=new File(FolderContent);
		File[] f=ff.listFiles();
		for(int i=0;i<f.length;i++){
			ar=new Artical();
			// get file name and convert to integer for sort by Descending
			filename=Integer.parseInt(f[i].getName().substring(0, f[i].getName().length()-4));
			ar=read(filename+"");  
			if(ar.toString().contains(str)){
				a.add(filename);  //add file name to list of integer
			}
			ar=null;
		}
		// sort data or file name by descending
		Collections.sort(a,Collections.reverseOrder());
		return a;
	}
	public static int TotalFile(){
		File f=new File(FolderContent);
		File[] fi=f.listFiles();
		return fi.length;
	}
	//=============== List all File name in folder Content ====================
	public static ArrayList<Integer> listFileName(){
		ArrayList<Integer> listfile=new ArrayList<>();
		File f=new File(FolderContent);
		File[] fi=f.listFiles();
		if(fi.length>0){
			for(File fa:fi){
				String s=new String(fa.getName().substring(0,fa.getName().length()-4));
				listfile.add(Integer.parseInt(s));
			}
			Collections.sort(listfile,Collections.reverseOrder());
		}
		return listfile;
	}
	//=============== Write new Id to File AutoId =============================
	public boolean write_AutoID(int id){
		File f=new File("AutoID"+File.separator+"AutoId.txt");
		try {
			fos=new FileOutputStream(f,true);
			DataOutputStream dos=new DataOutputStream(fos);
			dos.writeInt(id);
			dos.flush();
			dos.close();
			return true;
		} catch (FileNotFoundException e) {
			System.out.println("File Auto ID Not Found");
		} catch (IOException e) {
			System.out.println("Exception Write AutoID");
		}
		return false;
	}
	//============== Read last Id from File AutoId =============================
	public int Read_AutoID() throws IOException{
		File file=new File("AutoID"+File.separator+"AutoId.txt");
		int t=0;
		if(file.exists()){
			try{
				FileInputStream f=new FileInputStream(file);
				DataInputStream d=new DataInputStream(f);
				while(true){
					t=d.readInt();
				}
			}catch(Exception e){
				return t;
			}
		}
		else{
			write_AutoID(0);
		}
		return -1;
	}
	//============================== Copy File from source to dest ===========================
	public void copyFile(String pathsource,String pathdirs,String filename) throws IOException {
		 FileChannel inputChannel = null;
		 FileChannel outputChannel = null;
		 try{
			 
		    File source=new File(pathsource+File.separator+filename+".txt");
			File dir=new File(pathdirs+File.separator+filename+".txt");
			 inputChannel = new FileInputStream(source).getChannel();
			 outputChannel = new FileOutputStream(dir).getChannel();
			 outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
		 }catch(IOException e){
			 System.out.println("Error when copy file");
		 }catch(Exception e){
			 System.out.println("Error copy file");
		 }finally{
			 outputChannel.close();
			 inputChannel.close();
		 }
	 }
	//=============================== Restore =====================================
	public static ArrayList<Integer> ListRestore(){
		ArrayList<Integer> listfile=new ArrayList<>();
		File f=new File(FolderContent);
		File[] fi=f.listFiles();
		if(fi.length>0){
		
			for(File fa:fi){
				String s=new String(fa.getName().substring(0,fa.getName().length()-4));
				listfile.add(Integer.parseInt(s));
			}
			Collections.sort(listfile,Collections.reverseOrder());
		}
		return listfile;
	}
}
